package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;

public class NjnewsNewsAnalyse implements AnalyseNews {

	private static final String[] regex={ 
		"http://www.njnews.cn/news/[0-9]+-[0-9]+/[0-9]+/content_[0-9]+.htm" ,
		};

	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate() {
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();
		if (!isDetailPage(url)) {
		}

		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		title=doc.select("div.content_title").text();
		if(StringUtils.isBlank(title)){
					title=doc.select("title").text();
					if (title.contains("_")) {
						title=StringUtils.substringBefore(title, "_");
					}
		}
		date=DateUtils.matchDate(doc.select("div.bianji").text());
		if (date == null) {
			date=JSoupUtils.matchDate(doc, "来源：");
		}
		author=JSoupUtils.matchAuthor(doc, "来源:");
		doc.select(".location").remove();
		doc.select(".bianji").remove();
		content=HtmlCleaner.getContentHtml(url,doc.select("div.content_lf_content p"));
		if(StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select("div.words"));
		}
		news.setUrl(url);
		news.setTitle(title);
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);
		return news;
	}

	public static void main(String[] args) {
		NjnewsNewsAnalyse test=new NjnewsNewsAnalyse();

		String url="http://qx.longhoo.net/2014-09/12/content_11370045.htm";
		url=UrlArgumentTop.FromatUrl(url);
		System.out.println(url);
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(test.isDetailPage(url));
		NewsMeta parserHtml=test.parserHtml(meta);
		System.out.println(parserHtml);
	}

}
